#include "preHeader.h"
#include "SocialServerSession.h"
#include "SocialServerSessionHandler.h"
#include "GameServerSession.h"
#include "ClientMgr.h"
#include "GateServer.h"
#include "network/ConnectionManager.h"
#include "Game/TransMgr.h"

SocialServerSession::SocialServerSession()
: Session("SocialServerSession")
{
}

SocialServerSession::~SocialServerSession()
{
}

void SocialServerSession::CheckConnection()
{
	if (m_port.empty()) {
		return;
	}

	const auto& connPrePtr = GetConnection();
	if (connPrePtr && connPrePtr->IsActive()) {
		return;
	}
	if (!IsStatus(Idle)) {
		return;
	}

	auto connPtr = sConnectionManager.NewConnection(*this);
	connPtr->AsyncConnect(m_host, m_port);

	sSessionManager.AddSession(this);
}

void SocialServerSession::TransPacket(uint32 uid, const INetPacket& pck)
{
	NetPacket trans(CGT_TRANS_CLIENT_PACKET);
	trans << uid;
	PushSendPacket(trans, pck);
}

int SocialServerSession::HandlePacket(INetPacket *pck)
{
	return sSocialServerSessionHandler.HandlePacket(this, *pck);
}

void SocialServerSession::OnConnected()
{
	NetPacket req(CGT_REGISTER);
	req << sGameServerSession.sn();
	PushSendPacket(req);
	Session::OnConnected();
}

void SocialServerSession::OnShutdownSession()
{
	WLOG("Close SocialServerSession.");
	Session::OnShutdownSession();
}

void SocialServerSession::DeleteObject()
{
	ClearRecvPacket();
	ClearShutdownFlag();
	SetStatus(Idle);
}

void SocialServerSession::OnRecvPacket(INetPacket *pck)
{
	switch (pck->GetOpcode()) {
	case SGT_TRANS_CLIENT_PACKET:
		TransClientPacket(pck);
		delete pck;
		break;
	default:
		Session::OnRecvPacket(pck);
		break;
	}
}

void SocialServerSession::TransClientPacket(INetPacket *pck) const
{
	auto pSession = sTransMgr.GetClient(pck->Read<uint32>());
	if (pSession != NULL) {
		pSession->PushSendPacket(pck->CastReadableStringView());
	}
}

void SocialServerSession::SetHostPort(const std::string& host, const std::string& port)
{
	if (!m_port.empty() && !host.empty()) {
		if (m_host != host || m_port != port) {
			KillSession();
		}
	}
	m_host = host, m_port = port;
}

void SocialServerSession::SetGsGateSN(uint32 gsGateSN)
{
	NetPacket pack(CGT_UPDATE_GS_GATE_SN);
	pack << gsGateSN;
	PushSendPacket(pack);
}

int SocialServerSessionHandler::HandleRegisterResp(SocialServerSession *pSession, INetPacket &pck)
{
	pck.Take(pSession->m_handlerFlags, sizeof(pSession->m_handlerFlags));
	NLOG("Register to SocialServer Success.");
	return SessionHandleSuccess;
}

int SocialServerSessionHandler::HandlePushPacketToAllClient(SocialServerSession *pSession, INetPacket &pck)
{
	sClientMgr.BroadcastPacket2AllClient(pck.UnpackPacket());
	return SessionHandleSuccess;
}
